package com.example.springboot.handler;

import com.example.springboot.exception.BaseException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Description: controller全局异常处理类
 * 有两个@ExceptionHandler处理同一个异常的方法，@ControllerAdvice则优先于@RestControllerAdvice
 * @Author wenlinyu
 * @Date: 2020/12/16 15:11
 * @Version 1.0
 */
@ControllerAdvice(annotations = Controller.class)
public class ControllerExceptionHandler {

    /**
     * 当发生BaseException类异常时，进入该方法
     * @param e
     * @return
     */
    @ExceptionHandler({BaseException.class})
    public ModelAndView baseExceptionHandler(BaseException e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("code", e.getCode());
        mv.addObject("msg", e.getMsg());
        mv.setViewName("myerror");
        return mv;
    }

    /**
     * 当发生Exception类异常时，进入该方法
     * @param e
     * @return
     */
    @ExceptionHandler({Exception.class})
    public ModelAndView exceptionHandler(Exception e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("code", 99999);
        mv.addObject("msg", e.getMessage());
        mv.setViewName("myerror");
        return mv;
    }
}
